package be.sc.classicnetwork.controller.beans;

import java.beans.PropertyEditorSupport;

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import be.sc.classicnetwork.model.AbstractEntity;

/**
 * CodeEditor.
 */
public class EntityPropertyEditor extends PropertyEditorSupport {
    private Class<? extends AbstractEntity> targetClass;

    public EntityPropertyEditor(Class<? extends AbstractEntity> targetClass) {
	super();
	Assert.isAssignable(AbstractEntity.class, targetClass);
	this.targetClass = targetClass;
    }

    /**
     * @see java.beans.PropertyEditorSupport#setAsText(java.lang.String)
     */
    public void setAsText(String id) {
	if (!StringUtils.hasText(id)) {
	    setValue(null);
	} else {
	    AbstractEntity entity;
	    try {
		entity = (AbstractEntity) targetClass.newInstance();
	    } catch (InstantiationException e) {
		throw new IllegalArgumentException(e);
	    } catch (IllegalAccessException e) {
		throw new IllegalArgumentException(e);
	    }
	    entity.setId(id);
	    setValue(entity);
	}
    }

    /**
     * @see java.beans.PropertyEditorSupport#getAsText()
     */
    public String getAsText() {
	return (this.getValue() == null) ? "" : String.valueOf(((AbstractEntity) this.getValue()).getId());
    }

    /**
     * @see java.beans.PropertyEditorSupport#supportsCustomEditor()
     */
    public boolean supportsCustomEditor() {
	return true;
    }
}
